package com.hxkcloud.patient.recorder.view;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

/**
 * Created by william_sun on 2016-07-15.
 * Description:录音时检测手势的button
 */
public class AudioRecorderButton extends Button implements AudioManager.AudioStateListener {

    private static final int DISTANCE_Y_CANCEL = 50;
    private static final int STATE_NORMAL = 1;//默认状态
    private static final int STATE_RECORDING = 2;//录音状态
    private static final int STATE_WANT_TO_CANCEL = 3;//取消状态

    private int mCurState = STATE_NORMAL;
    //已经开始录音
    private boolean isRecording = false;

    private DialogManager mDialogManager;

    public AudioManager getmAudioManager() {
        return mAudioManager;
    }

    private AudioManager mAudioManager;

    private float mTime;

    //是否触发longClick
    private boolean mReady;

    private AudioRecorderLinearlayout.OnRecordingListener onRecordingListener;

    public void setOnRecordingListener(AudioRecorderLinearlayout.OnRecordingListener onRecordingListener) {
        this.onRecordingListener = onRecordingListener;
    }

    public AudioRecorderButton(Context context) {
        super(context);
        init();
    }

    public AudioRecorderButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AudioRecorderButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void init() {
        mDialogManager = new DialogManager(getContext());
        String dir = Environment.getExternalStorageDirectory() + "/recorder_audios";
        mAudioManager = AudioManager.getInstance(dir);
        mAudioManager.setOnAudioStateListener(this);

        setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (TextUtils.isEmpty(mAudioManager.getCurrentFilePath())) {
                    changeState(STATE_RECORDING);
                    mReady = true;
                    mAudioManager.prepareAudio();
                    AudioRecorderButton.this.getParent().requestDisallowInterceptTouchEvent(true);
                }
                return false;

            }
        });

        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (onRecordingListener != null && !TextUtils.isEmpty(mAudioManager.getCurrentFilePath()))
//                    onRecordingListener.click(mAudioManager.getCurrentFilePath());
//                play
            }
        });
    }

    /**
     * 获取音量大小的Runable
     */
    private Runnable mGetVoiceLevelRunable = new Runnable() {
        @Override
        public void run() {
            while (isRecording) {
                try {
                    Thread.sleep(100);
                    mTime += 0.1f;
                    mHandler.sendEmptyMessage(MSG_VOICE_CHANGED);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    };

    private static final int MSG_AUDIO_PREPARED = 0x110;
    private static final int MSG_VOICE_CHANGED = 0x111;
    private static final int MSG_DIAL0G_DIMISS = 0x112;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_AUDIO_PREPARED:
                    //显示应该在audio end prepared以后
                    mDialogManager.showRecordingDialog();
                    isRecording = true;
                    new Thread(mGetVoiceLevelRunable).start();
                    break;
                case MSG_VOICE_CHANGED:
                    mDialogManager.updateVoiceLevel(mAudioManager.getVoiceLevel(7));
                    break;
                case MSG_DIAL0G_DIMISS:
                    mDialogManager.dimissDialog();
                    break;
            }
        }
    };

    @Override
    public void wellPrepared() {
        mHandler.sendEmptyMessage(MSG_AUDIO_PREPARED);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (action) {
            case MotionEvent.ACTION_DOWN:

                break;
            case MotionEvent.ACTION_MOVE:
                if (isRecording) {
                    //根据x,y的坐标，判断是否想要取消
                    if (wantToCancel(x, y)) {
                        changeState(STATE_WANT_TO_CANCEL);
                    } else {
                        changeState(STATE_RECORDING);
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                AudioRecorderButton.this.getParent().requestDisallowInterceptTouchEvent(false);
                if (!mReady) {
                    reset();
                    return super.onTouchEvent(event);
                }

                if (!isRecording || mTime < 0.6f) {
                    mDialogManager.tooShort();
                    mAudioManager.cancel();
                    mHandler.sendEmptyMessageDelayed(MSG_DIAL0G_DIMISS, 1300);
                } else if (mCurState == STATE_RECORDING) {//正常录制结束
                    mDialogManager.dimissDialog();
                    mAudioManager.release();
                    if (onRecordingListener != null) {
                        if (mTime > (float) AudioManager.MAX_SECONDS / 1000)
                            mTime = (float) AudioManager.MAX_SECONDS / 1000;
                        onRecordingListener.onFinish(mTime, mAudioManager.getCurrentFilePath());
                    }


                } else if (mCurState == STATE_WANT_TO_CANCEL) {
                    mDialogManager.dimissDialog();
                    mAudioManager.cancel();
                }
                reset();
                break;
        }

        return super.onTouchEvent(event);
    }

    /**
     * 恢复状态及标志位
     */
    private void reset() {
        isRecording = false;
        mReady = false;
        mTime = 0;
        changeState(STATE_NORMAL);

    }

    private boolean wantToCancel(int x, int y) {
        if (x < 0 || x > getWidth()) {
            return true;
        }
        if (y < -DISTANCE_Y_CANCEL || y > getHeight() + DISTANCE_Y_CANCEL) {
            return true;
        }
        return false;
    }

    private void changeState(int state) {
        if (mCurState != state) {
            mCurState = state;
            switch (state) {
                case STATE_NORMAL:
//                    setBackgroundResource(R.drawable.btn_recorder_normal);
//                    setText(R.string.str_recorder_normal);
                    if (onRecordingListener != null)
                        onRecordingListener.stateNormal();

                    break;
                case STATE_RECORDING:
//                    setBackgroundResource(R.drawable.btn_recording);
//                    setText(R.string.str_recorder_recording);
                    if (onRecordingListener != null)
                        onRecordingListener.stateRecording();

                    if (isRecording) {
                        mDialogManager.recording();
                    }
                    break;
                case STATE_WANT_TO_CANCEL:
//                    setBackgroundResource(R.drawable.btn_recording);
//                    setText(R.string.str_recorder_want_cancel);
                    if (onRecordingListener != null)
                        onRecordingListener.stateWantToCancel();

                    mDialogManager.wantToCancel();
                    break;
            }
        }

    }

}
